#!/bin/sh

LOGIN=LoginServer.exe
CHANNEL=ChannelServer.exe
MSGR=MsgrServer.exe
WEB=WebServer.exe

getExePath() {

    fileName=$1
    exePath=""

    for folder in "Release" "Debug"
    do
        if [ -f "./bin/$folder/$fileName" ]; then
            exePath="./bin/$folder/$fileName"
            break
        fi
    done

    echo "$exePath"
}

case $1 in
    'start')
        loginPath=$(getExePath $LOGIN)
        channelPath=$(getExePath $CHANNEL)
        msgrPath=$(getExePath $MSGR)
        webPath=$(getExePath $WEB)

        if [ loginPath = "" ]; then
            echo "File $LOGIN not found."
            exit 1
        fi
        
        if [ channelPath = "" ]; then
            echo "File $CHANNEL not found."
            exit 1
        fi

        if [ msgrPath = "" ]; then
            echo "File $MSGR not found."
            exit 1
        fi

        if [ webPath = "" ]; then
            echo "File $WEB not found."
            exit 1
        fi

        echo "Starting Aura..."

        exec ./$loginPath&
        exec ./$channelPath&
        exec ./$msgrPath&
        exec ./$webPath&

        echo "Aura is now running.."
;;
    'stop')
        ps ax | grep -E "${LOGIN}|${CHANNEL}|${MSGR}|${WEB}" | awk '{print $1}' | xargs kill
        echo "Stopped Aura."
;;
    'restart')
        $0 stop
        $0 start
;;
    *)
        echo "Usage: start-all { start | stop | restart }"
;;
esac
